<template>
  <div class="reportform-container">
    <el-form ref="form" :model="requestParam" label-width="0px">
      <el-row>
        <el-col :span="8">
          <el-form-item prop="search">
            <el-select v-if="reportType === '3'" clearable @change="getTplRecordList" v-model="requestParam.node_type">
              <el-option :value="item.node_type" :label="item.status_name" v-for="item in nodeTypeList"
                :key="item.node_type">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4" :offset="12" class="align-right">
          <el-button @click="printReport" type="primary">导出数据</el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-table :data="reportFormList.list" ref="reportForm" style="width: 100%">
      <el-table-column type="selection"> </el-table-column>
      <el-table-column prop="tpl_name" label="业务名称"> </el-table-column>
      <el-table-column prop="created_by_name" label="发起人"> </el-table-column>
      <el-table-column v-if="reportType === '3'" prop="status_name" label="状态">
      </el-table-column>
      <el-table-column prop="updated_at" label="最后操作时间">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="checkDetail(scope.row)" type="text">查看</el-button>
          <el-button @click="deleteForm(scope.row)" type="text">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @current-change="handlePageChange" @size-change="handleSizeChange" :current-page="requestParam.page"
      :page-size="requestParam.page_size" layout="total,sizes,prev, pager, next, jumper" background
      :total="reportFormList.total_count" align="center">
    </el-pagination>
    <el-dialog title="选择打印模板" :visible.sync="dialogVisiblePrintFlag">
      <el-table ref="singleTable" :data="printTemplateList" highlight-current-row @current-change="handleCurrentChange"
        style="width: 100%">
        <el-table-column property="templete_name" label="模板名称">
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisiblePrintFlag = false">取 消</el-button>
        <el-button type="primary" @click="toPrintPage">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { userPermissionApi } from "@/services/UserPermission";
  import { CommonCheckApi } from "@/services/SystemSetting";
  export default {
    data() {
      return {
        // 报表类型，区分独立模式或流程模式，2为独立，3为流程
        reportType: "",
        requestParam: {
          tpl_name: "",
          node_type: "",
          project_id: '',
          is_page: 1,
          page: 1,
          page_size: 10
        },
        resetParam: {
          node_type: "",
          is_page: 1,
          page: 1,
          page_size: 10
        },
        reportFormList: {
          list: [],
          page: 1,
          total_count: 0
        },
        dialogVisiblePrintFlag: false,
        printTemplateList: [], // 打印弹窗的模版列表
        choosedRows: [],
        // 节点类型数据
        nodeTypeList: [],
        projectId: '',
        companyId: '',
        userId: ''
      };
    },
    watch: {
      $route(to, from) {
        this.requestParam.tpl_name = this.$route.query.tplName;
        this.reportType = this.$route.query.type;
        this.getTplRecordList();
      },
      '$store.state.choosedProject.project_id': function (val) {
        this.requestParam.project_id = val
        this.getTplRecordList()
      }
    },
    methods: {
      handleSizeChange(size) {
        this.requestParam.page_size = size;
        this.requestParam.page = 1;
        this.getTplRecordList();
      },
      handlePageChange(page) {
        this.requestParam.page = page;
        this.getTplRecordList();
      },
      search() {
        this.requestParam.page = 1;
        this.getTplRecordList();
      },
      reset() {
        let reset = JSON.parse(JSON.stringify(this.resetParam));
        this.requestParam = Object.assign(this.requestParam, reset);
        this.getTplRecordList();
      },
      // 跳转到详情
      checkDetail(row) {
        this.$router.push({
          path: "/reportFormDetail",
          query: {
            id: row.check_record_id
          }
        });
      },
      // 获取列表
      getTplRecordList() {
        CommonCheckApi.getTplRecordList({
          params: this.requestParam
        }).then(res => {
          if (res.code === 0) {
            this.reportFormList = res.data;
          }
        });
      },
      // 删除数据
      deleteForm(row) {
        this.$confirm("此操作将永久删除, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.deleteFormApi(row.check_record_id);
          })
          .catch(() => { });
      },
      deleteFormApi(id) {
        CommonCheckApi.deleteTplRecord({
          data: {
            check_record_id: id
          }
        }).then(res => {
          if (res.code === 0) {
            this.$message.success("删除数据成功");
            this.getTplRecordList();
          }
        });
      },
      // 获取节点类型下拉框列表
      getNodeBoxList() {
        CommonCheckApi.getNodeBoxList({
          params: {
            tpl_name: this.requestParam.tpl_name
          }
        }).then(res => {
          if (res.code === 0) {
            this.nodeTypeList = res.data.list;
          }
        });
      },
      // 打印报表
      printReport() {
        let selection = this.$refs.reportForm.selection;
        // if (selection.length === 0) {
        //   this.$message.warning("请选择数据");
        //   return;
        // }
        this.choosedRows = selection;

        userPermissionApi
          .printTemplateList({
            data: {
              templete_url: "reportForm",
              company_id: this.companyId,
              project_id: this.projectId
            }
          })
          .then(res => {
            if (res.code === 0) {
              this.dialogVisiblePrintFlag = true;
              this.printTemplateList = res.data;
            }
          });
      },
      handleCurrentChange(val) {
        this.dialogTableRow = val;
      },
      toPrintPage() {
        if (!this.dialogTableRow) return;
        if (Object.keys(this.dialogTableRow).length == 0) {
          return;
        }

        let systemName = this.dialogTableRow.categ_no;
        let suffix = ``;
        let chooseList = [];
        if (this.dialogTableRow.url_para) {
          chooseList = this.dialogTableRow.url_para.split(",");
        } else {
          this.$message.warning("输入参数为空");
          return;
        }

        chooseList.forEach(v => {
          // 首先拿到需要处理的参数列表，从选中的行中拿到参数对应的值，最后拼接起来
          let list = [];
          this.choosedRows.map(item => {
            list.push(item[v]);
          });
          if (list.length > 0) {
            let str = list.join(",");
            suffix += `${v}=${str}&`;
          }

        });
        // if(this.dialogTableRow.company_id!=='0'){
        //   suffix+=`company_id=${this.dialogTableRow.company_id}&`
        // }
        // if(this.dialogTableRow.project_id!=='0'){
        //   suffix+=`project_id=${this.dialogTableRow.project_id}&`
        // }

        // suffix = suffix.substring(0, suffix.length - 1);
        suffix += `companyId=${this.companyId}`
        suffix += `&userId=${this.userId}`
        suffix += `&projectId=${this.projectId}`
        let alink = document.createElement("a");
        alink.target = "_blank";
        let hrefUrl = `http://report.hibuilding.cn/ureport/preview?_u=file:${systemName}.ureport.xml&${suffix}`;

        console.warn(suffix);
        console.warn(hrefUrl);

        alink.href = hrefUrl;
        // alink.href="http://report.hibuilding.cn/ureport/preview?_u=12-16%E6%B5%8B%E8%AF%95%E6%A8%A1%E6%9D%BF&account=15622223333&pwd=hz666666&project_id=179&house_type=A&house_id=83941";
        alink.click();
        alink.remove();
      }
    },
    created() {
      
      this.requestParam.tpl_name = this.$route.query.tplName;
      this.reportType = this.$route.query.type;
      let userInfo = JSON.parse(window.localStorage.userInfo) || {}
      this.projectId = Number(
        JSON.parse(window.localStorage.getItem("choosedProject")).project_id
      );
      this.requestParam.project_id = this.projectId
      this.companyId = userInfo.comp_id
      this.userId = userInfo.user_id
      this.getNodeBoxList();
      this.getTplRecordList();
    },
    mounted() { }
  };
</script>
<style scoped lang="scss">
  .reportform-container {
    padding: 20px;

    .el-pagination {
      margin-top: 20px;
    }

    .el-form {
      height: 65px;
    }

    .el-input {
      width: 70%;
    }
  }
</style>